home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9015 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  58 lines

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Calling a Function Twice from a printf statement.
  5. Date: 7 Mar 1996 17:49:04 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4hnp50$ua@umbc9.umbc.edu>
  8. References: <4he6q9$6r6@newsbf02.news.aol.com>
  9. NNTP-Posting-Host: umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. Razine <razine@aol.com> wrote:
  13. |> I am trying to call a function twice from my program on the same printf
  14. |> line and have run into a small problem.  i was wondering if someone can
  15. |> explain how to fix it.
  16. |> 
  17. |> void main(void) {
  18.  
  19. Well as soon as you give an incorrect definition for main() that immediately
  20. introduces possible undefined behavior to your program. Make it
  21. 'int main (void)'.
  22.  
  23. |>    printf("First Number is %d , the Second s %d \n",num(0),num(1));
  24.  
  25. Not giving a prototype for a variadic function like printf() can lead
  26. to unexpected results as well. Please #include <stdio.h>.
  27.  
  28. |> }
  29. |> 
  30. |> int num(int index) {
  31. |>    int return_number;
  32. |>    
  33. |>    switch(index) {
  34. |>        case 0 : return_number=0;
  35. Add:               break;
  36. |>        case 1 : return_number=1;
  37. Add:               break;
  38. |>                        }
  39. |>    return(return_number);
  40.  
  41. Note that this is probably garbage if 'index' is other than 0 or 1.
  42. |> }
  43. |> 
  44. |> Now with this function, the printf line will display 0 for the first one
  45. |> and garbage for the second one..  I then thought if I made the variable
  46. |> return_number a static variable it would have fixed it but then when i
  47. |> made the change the printf line would give me zero for both of them.  Any
  48. |> ideas?
  49.  
  50. Static is certainly the *WRONG* choice since that will make the function
  51. unable to be called twice in 1 printf() statement. This is due to the
  52. static variable being overridden on subsequent calls to the function.
  53. The solution is to use switch() properly and define functions properly.
  54. -- 
  55. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  56.  
  57. Jonas J. Schlein  (schlein@gl.umbc.edu)
  58.